package com.study.leetcode;

import java.util.Arrays;
import java.util.Comparator;

//https://leetcode-cn.com/problems/merge-intervals/
public class Solution_56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
        int[][] tempRes = new int[intervals.length][2];
        int index = -1;
        for (int[] interval : intervals) {
            if (index == -1 || interval[0] > tempRes[index][1]) {
                tempRes[++index] = interval;
            } else {
                tempRes[index][1] = Math.max(tempRes[index][1], interval[1]);
            }
        }
        return Arrays.copyOf(tempRes, index + 1);
    }

    public static void main(String[] args) {
        int[][] ints = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        Solution_56 solution56 = new Solution_56();
        solution56.merge(ints);
    }
}
